package cn.itcast.mybatis.jdbc;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.Before;
import org.junit.Test;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;


public class DemoDruidPool {
	
	DruidDataSource datasource = null;
	
	@Before
	public void init() throws IOException {
		
		datasource = new DruidDataSource();
		
//		Properties properties = new Properties("../../config/db.properties");
//		datasource.setUrl("jdbc:mysql://localhost/exam?characterEcoding=utf-8");
//		datasource.setDriverClassName("com.mysql.jdbc.Driver");
//		datasource.setUsername("root");
//		datasource.setPassword("root");
		
		//把配置信息放到配置文件中
		
//		InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("/config/db.properties");
		
		//D:\暑期作业与笔记\camp\code\day30\src\cn\itcast\mybatis\jdbc\JdbcTest.java
		//D:\暑期作业与笔记\camp\code\day30\config\db.properties
		FileReader resourceAsStream = new FileReader("D:\\暑期作业与笔记\\camp\\code\\day30\\config\\Druid.properties");
		
		Properties properties = new Properties();
		
		properties.load(resourceAsStream);
		
		datasource.configFromPropety(properties);
	}
	
	//可以不用考虑关闭connection呢，数据池会帮我们关闭
	@Test
	public void DruidPoolTest() throws SQLException {
		
		//获取连接
		DruidPooledConnection connection = datasource.getConnection();
		
		//写sql语句
		String sql = "select * from student where sid = ?";
		
		//通过预处理语句，获取sql
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		
		//用预处理语句，设置参数
		preparedStatement.setInt(1, 3);
		
		//获得结果集
		ResultSet executeQuery = preparedStatement.executeQuery();
		
		//遍历结果集
		while(executeQuery.next()) {
			
			System.out.println(executeQuery.getString("sid")+" "+executeQuery.getString("name"));
		}
		
	}
	
}	
